import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { getDelItemAction, getChangeItemFinishedAction } from './../store/actionCreators'
import { connect } from 'react-redux'

class Item extends Component {
    constructor(props) {
        super(props)
        this.state = {
            showDelBtn: false
        }
    }
    static propTypes = {
        todo: PropTypes.object.isRequired,  // 单条数据
    }


    render() {
        const { todo, delTodo, updateTodo } = this.props;
        const { showDelBtn } = this.state;
        return (
            <li
                className="todos-item"
                onMouseOver={() => this._showBtn(true)}
                onMouseOut={() => this._showBtn(false)}
            >
                <label className="todos-item-title">
                    <input type="checkbox" checked={todo.finished} onChange={() => updateTodo(todo.id, !todo.finished)} />
                    <span>{todo.title}</span>
                </label>
                <button onClick={() => delTodo(todo.id)} style={{ display: showDelBtn ? 'inline-block' : 'none' }}>删 除</button>
            </li>
        )
    }

    // 处理按钮显示隐藏
    _showBtn(flag) {
        this.setState({
            showDelBtn: flag
        })
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        delTodo(id) {
            const action = getDelItemAction(id);
            dispatch(action);
        },
        updateTodo(id,finished) {
            const action = getChangeItemFinishedAction(id, finished);
            dispatch(action);
        }
    }
}

export default connect(null, mapDispatchToProps)(Item)